import { deepMerge, showToast } from "../utils";
import { storage } from "../utils/storage"
import { getUserPerson, mini, refreshTokenApi, updatePerson } from "../api/user";
import { director } from "cc";
import { miniLogin, miniShare, shareApp } from "./wx";
import DataManager from "../Runtime/DataManager";
import { useSocket } from "./socket";
const wx = window['wx']
const socket = useSocket()
// 本地缓存
const userStore = function () {
    // 标识
    let token = storage.get("token") || "";
    // 标识
    let login_loading = false;

    // 设置标识
    function setToken(data) {
        token = data.token;
        // 访问
        storage.set("token", data.token, data.expire - 5);
        // storage.set("token", data.token, 5)
        // 刷新
        storage.set("refreshToken", data.refreshToken, data.refreshExpire - 5);
    }

    // 刷新标识
    async function refreshToken() {
        return refreshTokenApi({
            refreshToken: storage.get("refreshToken"),
        })
            .then((res) => {
                console.log(res, 'refreshToken')
                setToken(res);
                return res.token;
            });
    }
    let info = null
    // 用户信息
    if (storage.get("userInfo")) {
        info = JSON.parse(storage.get("userInfo"));
    }


    // 设置用户信息
    function set(value) {
        info = value;
        storage.set("userInfo", JSON.stringify(value));
    }

    // 更新用户信息
    async function update(data) {
        set(deepMerge(info, data));
        return updatePerson(data)
    }

    // 清除用户
    function clear() {
        storage.remove("userInfo");
        storage.remove("token");
        storage.remove("refreshToken");
        token = "";
        DataManager.Instance.room = null
        info = undefined;
        socket.disconnect()
    }
    function login() {
        if (typeof (wx) !== "undefined") {
            return new Promise<void>((resolve, reject) => {
                if (login_loading) return
                login_loading = true
                DataManager.Instance.controllerManager.showLoading("登录中")
                miniLogin().then(async data => {
                    mini(data).then(async res => {
                        login_loading = false
                        this.setToken(res);
                        // 获取用户信息
                        await this.get();
                        DataManager.Instance.controllerManager.hideLoading()
                        resolve()
                    }).catch(err => {
                        login_loading = false
                        reject(err)
                        showToast(err.message)
                        DataManager.Instance.controllerManager.hideLoading()
                        console.log(err, "err")
                    })
                }).catch(err => {
                    DataManager.Instance.controllerManager.hideLoading()
                    reject(err)
                })
            })

        }
    }
    function share(query = '') {
        if (typeof (wx) !== "undefined") {
            miniShare(query)
        }
    }
    function shareAppMessage(query=''){
        if (typeof (wx) !== "undefined") {
            shareApp(query)
        }
    }
    // 退出
    function logout() {
        clear();
        
        director.loadScene('login')
    }

    // 获取用户信息
    async function get() {
        return getUserPerson()
            .then((res) => {
                if (res) {
                    set(res);
                }
                return res;
            })
            .catch(() => {
                logout();
            });
    }

    return {
        token,
        setToken,
        refreshToken,
        info,
        get,
        set,
        update,
        logout,
        login,
        share,
        shareAppMessage
    };
};

export { userStore };
